import requests
import json

# 后端服务URL
base_url = "http://localhost:8080"

# 登录获取token
def login():
    print("正在登录...")
    login_url = f"{base_url}/login"
    login_data = {
        "username": "admin",
        "password": "admin123",
        "code": "",
        "uuid": ""
    }
    headers = {'Content-Type': 'application/json'}
    
    try:
        response = requests.post(login_url, headers=headers, data=json.dumps(login_data))
        response_data = response.json()
        
        if response.status_code == 200 and 'token' in response_data:
            token = response_data['token']
            print("登录成功")
            return token
        else:
            print(f"登录失败: {response_data}")
            return None
    except Exception as e:
        print(f"登录请求异常: {e}")
        return None

# 调用项目列表API
def test_api(token):
    print("\n正在调用项目列表API...")
    url = f"{base_url}/admin/autotest/projects"
    headers = {"Authorization": f"Bearer {token}"}
    
    try:
        response = requests.get(url, headers=headers)
        print(f"响应状态码: {response.status_code}")
        
        # 尝试将响应保存到文件
        with open('simple_api_response.json', 'w', encoding='utf-8') as f:
            f.write(response.text)
        print("响应已保存到 simple_api_response.json")
        
        # 尝试解析JSON
        try:
            data = response.json()
            print("\n响应结构检查:")
            print(f"- 包含code字段: {'code' in data}")
            print(f"- 包含message字段: {'message' in data}")
            print(f"- 包含data字段: {'data' in data}")
            
            if 'data' in data and isinstance(data['data'], dict):
                print(f"- data包含pagination: {'pagination' in data['data']}")
                
                if 'pagination' in data['data'] and isinstance(data['data']['pagination'], dict):
                    pagination = data['data']['pagination']
                    print(f"  - pagination包含total: {'total' in pagination}")
                    print(f"  - pagination包含page: {'page' in pagination}")
                    print(f"  - pagination包含page_size: {'page_size' in pagination}")
                    print(f"  - pagination包含items: {'items' in pagination}")
        except Exception as e:
            print(f"解析JSON失败: {e}")
            
    except Exception as e:
        print(f"API请求异常: {e}")

if __name__ == "__main__":
    token = login()
    if token:
        test_api(token)
    print("\n测试结束")